Is the following OK?
Object obj; String str = "Yertle" ; obj = str; ((YouthBirthday)obj).greeting();
No.
instanceof
OperatorObject obj; YouthBirthday ybd = new YouthBirthday( "Ian", 4 ); String str = "Yertle"; obj = ybd; if ( obj instanceof YouthBirthday ) ((YouthBirthday)obj).greeting(); else if ( obj instanceof String ) System.out.print( (String)obj );
A typecast is used to tell the compiler what is really
in a variable that itself is not specific enough.
You have to tell the truth.
In a complicated program,
a reference variable might end up with any of several
different objects, depending on the input data or other
unpredictable conditions.
To deal with this, the instanceof
operator is used.
variable instanceof Class
This operator evaluates to true
or false
depending on whether the variable refers to an object of
type Class.
Also, instanceof
will return true
if variable
is a child of Class
.
It can also be a grandchild or greatgrandchild or ...
of the class.
For example in the above fragment,
instanceof
is used to ensure that the object
pointed to bye obj
is used correctly.
Will the following work?
Object obj; YouthBirthday ybd = new YouthBirthday( "Ian", 4 ); String str = "Yertle"; obj = ybd; if ( obj instanceof Card ) // Note changes here ((Card)obj).greeting(); else if ( obj instanceof String ) System.out.print( (String)obj );